<?php

if (!defined('BASEPATH'))
exit('No direct script access allowed');

class Layout_m extends Base_model {
	public $primary_key = 'layout_id';
	protected $validate = array(
	array( 'field' => 'edit[layout_name]',
	'label' => 'edit[layout_name]',
	'rules' => 'required' ),
	);
	
	function parse_from_url($uri = '', $is_loop = TRUE)
	{
		$links = $this->order_by('can_delete desc')->get_many_by();
		if($uri =='')
			$uri = implode('/', $this->uri->segments);
		$layout = FALSE;

		$class = $this->router->fetch_class();
		$method = $this->router->fetch_method();

		if($class =='uindex')
		{
			if($method =='category')
			{
				$layout = new stdClass();
				$layout->layout_id = 3;
				$layout->file_name = 'cateparent';
			}
		}

		if(isset($links) && $links)
		{
			
			foreach($links as $link)
			{
				$key = $link->layout_uri;
				// $link_redirect = FALSE;
				$val = $link->file_name;
				// Convert wild-cards to RegEx
				$key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));
				// Does the RegEx match?
				if (preg_match('#^'.$key.'$#', $uri))
				{
					$layout = $link;
					// Do we have a back-reference?
					if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE)
					{
						$val = preg_replace('#^'.$key.'$#', $val, $uri);
						$layout = $link;
					}
					// return $link;
				}
			}
			
		}
		if($layout == FALSE && $is_loop == TRUE)
		{
		// prd($link_redirect);
			return $this->parse_from_url($this->uri->ruri_string(), FALSE);
		}
		
		return $layout;
	}
}